package com.onlinemarket.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OnlineMarketUtil {

	private static final OnlineMarketUtil ONLINE_MARKET_UTIL=new OnlineMarketUtil();
	
	private OnlineMarketUtil() {
	}
	
	public static OnlineMarketUtil getOnlineMarketUtil(){
		return ONLINE_MARKET_UTIL;
	}
	
	public Map<String, Object> buildJbdcNamedParamValue(Object object){
		Map<String, Object> jdbcNamesParamValueMap = new HashMap<String, Object>();
		if(object!=null){
			Method[] gettrMethods = fetchGetterMethod(object);
			for(Method getterMethod : gettrMethods){
				String fieldName = getterMethod.getName().substring(3);
				fieldName = (fieldName.charAt(0)+"").toLowerCase()+fieldName.substring(1);
				try {
					jdbcNamesParamValueMap.put(fieldName,getterMethod.invoke(object));
				} catch (IllegalAccessException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				} catch (InvocationTargetException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		return null;
	}
	
	public Method[] fetchGetterMethod(Object object){
		List<Method> methodList = new ArrayList<Method>();
		if(object!=null){
			Method[] methods = object.getClass().getMethods();
			for(Method method : methods){
				if(method.getName().startsWith("get")){
					methodList.add(method);
				}
			}
		}
		return methodList.toArray(new Method[0]);
	}
}
